package com.updesignsz.admin.util.image;

import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

public class ImageBase64Util {


    public static String saveAsImage(String imgBase64, HttpServletRequest request) {
        String fileName = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgBase64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 创建文件夹
            String uploadPath = FileUploadUtil.getRealPath(request);
            FileUtil.createFileDir(uploadPath);
            //this.url = UUID.randomUUID().toString() + imgFilePath.substring(imgFilePath.lastIndexOf(".")).toLowerCase();
            fileName = UUID.randomUUID().toString() + ".jpg";
            String fullFileName = uploadPath + fileName;

            // 生成图片
            OutputStream out = new FileOutputStream(fullFileName);
            out.write(bytes);
            out.flush();
            out.close();

            // 生成缩略图
//            thumbnailImage(fullFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }


    public static String saveAsImage(byte[] bytes, String uploadPath) {
        String fileName = null;
        try {
//            BASE64Decoder decoder = new BASE64Decoder();
//            // Base64解码
//            byte[] bytes = decoder.decodeBuffer(imgBase64);
//            for (int i = 0; i < bytes.length; ++i) {
//                if (bytes[i] < 0) {// 调整异常数据
//                    bytes[i] += 256;
//                }
//            }
            // 创建文件夹
//            String uploadPath = FileUploadUtil.getRealPath(request);
            FileUtil.createFileDir(uploadPath);
            //this.url = UUID.randomUUID().toString() + imgFilePath.substring(imgFilePath.lastIndexOf(".")).toLowerCase();
            fileName = UUID.randomUUID().toString() + ".jpg";
            String fullFileName = uploadPath + fileName;

            // 生成图片
            OutputStream out = new FileOutputStream(fullFileName);
            out.write(bytes);
            out.flush();
            out.close();

            // 生成缩略图
            thumbnailImage(fullFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 生成缩略图
     * @param fileName
     */
    private static void thumbnailImage(String fileName) {
        if (fileName == null) {
            return;
        }

        int width = 75;
        int height = 50;

//        String size = null;
//        if (size == null) {
//            width = 75;
//            height = 50;
//        } else {
//            String[] s = size.split("\\*");
//            if (s != null && s.length > 1) {
//                width = Integer.valueOf(s[0]);
//                height = Integer.valueOf(s[1]);
//            }
//        }

        ImageUtil.thumbnailImage(fileName, width, height);
    }

//    public static String downloadFile(String media_id, HttpServletRequest request) throws Exception {
//
//        if(StringUtil.isEmpty(media_id)){
//            throw new Exception("no Upload");
//        }
//
//        InputStream in = null;
//        FileOutputStream out = null;
//        HttpURLConnection conn = null;
//        File file = null;
//        /**构建图片保存的目录**/
//        String logoPathDir = FileUploadUtil.getCurrentRelativePath();
//        if (!logoPathDir.startsWith("/")) {
//            logoPathDir = "/" + logoPathDir;
//        }
//        /**得到图片保存目录的真实路径**/
//        String uploadPath = request.getSession().getServletContext().getRealPath(logoPathDir);
//
//        String fileName = System.currentTimeMillis() + ".jpg";
//
//        try {
//            if (PublicUtil.map.containsKey("expires_in")) {
//                Long dateLong = Long.parseLong(PublicUtil.map.get("expires_in").toString());
//                if (dateLong <= System.currentTimeMillis()) {
//                    getAccessToken();
//                }
//            } else {
//                getAccessToken();
//            }
//            String access_token = PublicUtil.map.get("access_token").toString();
//            log.info("参数传入的media_id值："+media_id+",access_token的值："+access_token);
//            String downloadurl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + media_id;
//            URL url = new URL(downloadurl);
//            conn = (HttpURLConnection) url.openConnection();
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);
//            conn.setRequestMethod("GET");
//
//            in = conn.getInputStream();
//            if(in != null){
//                file = new File(uploadPath+"/"+fileName);
//            }
//            out = new FileOutputStream(file);
//            if(out!=null){
//                int c = in.read();
//                while(c!=-1){
//                    out.write(c);
//                    c = in.read();
//                }
//            }
//        }  catch (Exception e) {
//            log.error(e);
//        }finally{
//            if(conn!=null){
//                conn.disconnect();
//            }
//            /*
//             * 必须关闭文件流
//             * 否则JDK运行时，文件被占用其他进程无法访问
//             */
//            try {
//                in.close();
//                out.close();
//            } catch (IOException execption) {
//                log.error(execption);
//            }
//        }
//        return logoPathDir+"/"+fileName;
//    }

//    /**
//     * 获取微信
//     * @throws Exception
//     */
//    private static void getAccessToken() throws Exception  {
//        String content = HttpUtil.httpGet(WeChatUtil.weChat_url, PublicUtil.encoding);
//        if (StringUtil.isNotEmpty(content)) {
//            JSONObject jsonObject = JSONObject.fromObject(content);
//            if (jsonObject.has("access_token")) {
//                PublicUtil.map.put("access_token", jsonObject.getString("access_token"));
//                PublicUtil.map.put("expires_in", DateUtil.getDateLong());
//            }
//        }
//    }
}
